package com.sl.biz.modular.process.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.google.common.collect.Lists;
import com.sl.biz.modular.process.controller.response.ProcessComponentGroupVO;
import com.sl.biz.modular.process.controller.response.ProcessComponentVO;
import com.sl.biz.modular.process.service.ProcessComponentBizService;
import com.sl.core.domain.dto.ProcessComponentDTO;
import com.sl.core.utils.JsonUtil;
import com.sl.core.engine.ProcessEngine;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@AllArgsConstructor
public class ProcessComponentBizServiceImpl implements ProcessComponentBizService {

    @Override
    public List<ProcessComponentGroupVO> list() {
        List<ProcessComponentDTO> list = ProcessEngine.INSTANCE.pluginRegistry().list();
        List<ProcessComponentVO> processComponentVOS = JsonUtil.toList(list, ProcessComponentVO.class);

        if (CollUtil.isEmpty(processComponentVOS)) {
            return Collections.emptyList();
        }

        Map<String, List<ProcessComponentVO>> map = processComponentVOS.stream().collect(Collectors.groupingBy(ProcessComponentVO::getGroupCode));
        List<ProcessComponentGroupVO> res = Lists.newArrayList();
        for (Map.Entry<String, List<ProcessComponentVO>> entry : map.entrySet()) {
            String k = entry.getKey();
            List<ProcessComponentVO> v = entry.getValue();
            ProcessComponentGroupVO p = new ProcessComponentGroupVO();
            p.setCgCode(k);
            p.setCgName(CollUtil.get(v, 0).getGroupName());
            p.setChildren(v);
            res.add(p);
        }
        return res;
    }
}


